﻿using AutoMapper;
using Hotel.Common;
using Hotel.Domain;
using Hotel.IRepository;
using Hotel.IServices;
using Hotel.IServices.RequestDTO;
using Hotel.IServices.ResponseDTO;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hotel.Services
{
    public class LoginServies: ILoginServies
    {
        private readonly IBaseRepository<User> UserRepository;
        private readonly ILogger<LoginServies> logger;
        private readonly IMapper mapper;

        public LoginServies(IBaseRepository<User> userRepository, ILogger<LoginServies> logger, IMapper mapper)
        {
            UserRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task<ApiResult> LoginGoodsAsync(AddUserAsyncDto dto)
        {
            var info = new ApiResult<GetLoginInfoReDto>("登录失败");
            info.data.LoginErrorNum = 0;
            var user = await UserRepository.GetAllAsync(p => p.UserName == dto.UserName);
            if (user.Count == 0)
            {
                info.msg = "用户不存在";
                info.code = StatusCodeEnum.DataNotExist;
                return info;
            }

            if (user.Where(p=>p.UserPwd==dto.UserPwd).ToList().Count==0)
            {

              
                info.msg = "密码错误";
                info.code = StatusCodeEnum.Fail;
                info.data.LoginErrorNum = info.data.LoginErrorNum + 1;
                info.msg="密码错误,你还有"+(3-info.data.LoginErrorNum)+"次机会";
                if (info.data.LoginErrorNum==3)
                {
                    info.msg = "密码错误次数过多，账号已被锁定";
                }
             
                return info;
                
            }
            else
            {
                info.msg = "登录成功";
                info.code = StatusCodeEnum.Ok;
                return info;
            }

        }

        /// <summary>
        /// 生成 JWT Token（令牌）
        /// </summary>
        /// <returns></returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }

        /// <summary>
        ///用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async  Task<ApiResult> UserLoginAsync(AddUserAsyncDto dto)
        {
           var info= new ApiResult<UserLoginAsyncDto>("登录失败");

         var user=   await UserRepository.GetAllAsync(p => p.UserName == dto.UserName);
            if (user.Count==0)
            {

                info.msg = "用户不存在";
                info.code = StatusCodeEnum.DataNotExist;
                return info;
            }

            if(user.Where(p=>p.UserPwd==dto.UserPwd).ToList().Count==0)
            {
                info.msg = "密码不对";
                info.code = StatusCodeEnum.Fail;
                return info;
            }
            else
            {
                //生成token
                var token= CreateTokenString();
                info.msg = "登录成功";
                info.code = StatusCodeEnum.Ok;
               info.Token = token;
                return info;
            }
        }
    }
}
